"""
File Name: Pycharm
Description:   base_bot 浏览器做任务
Author: Panwj
Date: 2025/9/6 6:17
"""
import json
import os
import random
import time
import uuid
from enum import Enum

import requests
from DrissionPage._configs.chromium_options import ChromiumOptions
from DrissionPage._pages.chromium_page import ChromiumPage
from fake_useragent import UserAgent
from loguru import logger

ROOT_PATH = os.path.dirname(os.path.abspath(__file__))


class Action(Enum):
    HOME_VIEW_ACTION = "view_home_post"  # 首页浏览
    POST_VIEW_ACTION = "view_post"  # 帖子浏览
    LIKE_POST_ACTION = "like_post"  # 点赞主贴
    LIKE_COMMENT_ACTION = "like_comment"  # 点赞评论
    COMMENT_POST_ACTION = 'reply_post'  # 评论主贴
    COMMENT_COMMENT_ACTION = 'reply_comment'  # 评论评论

    def __init__(self, c_t):
        self._content_type = c_t

    @property
    def content_type(self):
        return Action.HOME_VIEW_ACTION.value


class BaseBot(object):
    name = '__base_bot__'

    def __init__(self):
        self.base_job_api = 'http://127.0.0.1:5000/job/api/v1/task/get_job?site_name=%s'
        self.home_url = None
        self.is_login = False
        self.is_active = False  # 是否活跃
        self.active_interval = (60, 120)  # 活跃周期
        self.active_action = Action.HOME_VIEW_ACTION.value
        self.page = None

    def check_post_exists(self, post_url):
        """
        校验帖子是否存在，帖子不存在不继续做任务
        :param post_url:
        :return:
        """

    def random_ua_list(self):
        ua_list = []
        for i in range(10):
            uas = [UserAgent().getChrome, UserAgent().getFirefox, UserAgent().getEdge, UserAgent().getOpera]
            for ua in uas:
                if ua["type"] == 'desktop' and ua['os'] == 'Windows':
                    ua_list.append(ua['useragent'])
        return list(set(ua_list))

    def get_proxy_v2(self):
        return None

    def load_page(self):
        try:
            co = ChromiumOptions().auto_port(True)
            co.incognito()  # 无痕模式
            # co.headless()  # 无头模式
            # user_data_dir = f"./user_data/{str(uuid.uuid4())}"
            co.set_argument('--no-sandbox')  # 无沙盒模式
            # co.set_argument('--headless', 'new')
            # co.set_argument('browser_path', '/usr/bin/google-chrome')
            # co.set_user_data_path(user_data_dir)  # 隔离用户数据
            # ========================
            # co.set_argument('--start-maximized')
            # co.set_argument('--window-size', '1500,800')  # 窗口大小会影响列表页获取数据的数量
            # ========================
            co.set_argument('--window-size', '1000,600')
            co.headless = False
            # # 设置 HTTP 代理
            # proxy_dict = get_proxy()
            proxy_dict = self.get_proxy_v2()
            if proxy_dict:
                proxy = f"http://{proxy_dict['ip']}:{proxy_dict['port']}"
                logger.info(f"设置代理: {proxy}")
                co.set_proxy(proxy)
            # co.set_proxy('http://127.0.0.1:7890')
            login_page = ChromiumPage(co)
            # 需要pc端的ua
            # ua_list = self.random_ua_list()
            # if ua_list:
            #     ua = random.choice(ua_list)
            # # 概率较低
            # else:
            ua = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/139.0.0.0 Safari/537.36 Edg/139.0.0.0"
            print(ua)
            login_page.set.user_agent(ua)
            self.page = login_page
        except Exception as e:
            print(f"创建登录页面失败: {e}")
            return None

    def login(self):
        # 登录账号
        pass

    def clear_expire_account(self):
        """
        清除失效账号
        :return:
        """

    def job(self):
        """
        读取动作任务
        :return:
        """
        while True:
            try:
                resp = requests.get(self.base_job_api % self.name, timeout=5)
                if resp.status_code == 200:
                    if resp.json()['code'] == 404:
                        logger.warning("暂时没有可执行的任务")
                        time.sleep(10)
                    else:
                        return json.loads(resp.json()['data'])
            except Exception as e:
                logger.error("获取任务异常！")
                time.sleep(5)

    def random_chose_account(self):
        """
        选择一个账号做动作
        条件：
        这个账号未做个当前帖子的任务
        选择当前活动次数过少的账号
        :return:
        """
        # todo 统计每个账号任务量，限制账号任务数，同一账号，不能同时做多个任务
        cookies = []
        cookie_file_path = os.path.join(ROOT_PATH, os.path.pardir)
        with open(f"{cookie_file_path}/account/{self.name.lower()}/cookie.txt", "r", encoding="utf-8") as f:
            for line in f.readlines():
                cookies.append(json.loads(line))
        random.shuffle(cookies)
        if cookies:
            self.__load_account(cookies[0])
        else:
            logger.error("没有充足的cookie使用！！！")

    def __load_account(self, cookies):
        self.page.get(self.home_url)
        self.page.set.cookies(cookies)
        self.page.refresh()
        logger.info(f"{self.name} Cookies 加载成功")
        time.sleep(5)
        return True
        pass

    def comment_post(self, post_url, comment_content):
        pass

    def like_post(self, post_url):
        pass

    def dislike_post(self, post_url):
        pass

    def like_comment(self, url):
        pass

    def comment_comment(self, url, comment_content, by_comment_content):
        pass

    def start_action(self):
        while True:
            try:
                json_job = self.job()
                if json_job:
                    job_size = json_job.get('job_size', 1)
                    for each_job in range(job_size):
                        try:
                            self.load_page()
                            self.page.get(self.home_url)
                            self.random_chose_account()
                            action = json_job['action'].lower()
                            url = json_job['url']
                            content = json_job['comment_content']
                            by_comment_content = json_job['by_comment_content']

                            if action == Action.COMMENT_POST_ACTION.value:
                                self.comment_post(url, content)
                            elif action == Action.LIKE_POST_ACTION.value:
                                self.like_post(url)
                            elif action == Action.LIKE_COMMENT_ACTION.value:
                                self.like_comment(url)
                            elif action == Action.COMMENT_COMMENT_ACTION.value:
                                self.comment_comment(url, content, by_comment_content)
                        except Exception as e:
                            logger.error(f"做任务时出现异常，异常原因：{str(e)}")
                        finally:
                            self.page.quit()
            except Exception as e:
                logger.error(f"任务出现异常，及时排查！{str(e)}")
            finally:
                if self.page:
                    self.page.quit()
